# -*- coding: utf-8 -*-

import torch
import torch.nn as nn


def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, block_gates, input_planes, output_planes, stride=1, down_sample=None):
        super(BasicBlock, self).__init__()

        self.block_gates = block_gates
        self.conv1 = conv3x3(input_planes, output_planes, stride)
        self.bn1 = nn.BatchNorm2d(output_planes)
        self.relu1 = nn.ReLU(inplace=False)  # To enable layer removal inplace must be False
        self.conv2 = conv3x3(output_planes, output_planes)
        self.bn2 = nn.BatchNorm2d(output_planes)
        self.relu2 = nn.ReLU(inplace=False)
        self.down_sample = down_sample
        self.stride = stride

    def forward(self, x):
        residual = out = x

        if self.block_gates[0]:
            out = self.conv1(x)
            out = self.bn1(out)
            out = self.relu1(out)

        if self.block_gates[1]:
            out = self.conv2(out)
            out = self.bn2(out)

        if self.down_sample is not None:
            residual = self.down_sample(x)

        out += residual
        out = self.relu2(out)

        return out


class ResNet(nn.Module):
    def __init__(self, block, block_numbers, num_classes=10):
        super(ResNet, self).__init__()

        # Each layer manages its own gates
        self.layer_gates = [[[True, True] for _ in range(block_number)]
                            for block_number in block_numbers]
        self.in_planes = 16  # 64
        self.conv1 = nn.Conv2d(3, self.in_planes, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_planes)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = self._make_layer(self.layer_gates[0], block, 16, block_numbers[0])
        self.layer2 = self._make_layer(self.layer_gates[1], block, 32, block_numbers[1], stride=2)
        self.layer3 = self._make_layer(self.layer_gates[2], block, 64, block_numbers[2], stride=2)
        self.avgpool = nn.AvgPool2d(8, stride=1)
        self.fc = nn.Linear(64 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                torch.nn.init.kaiming_normal_(m.weight)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, layer_gates, block, planes, blocks, stride=1):
        down_sample = None
        if stride != 1 or self.in_planes != planes * block.expansion:
            down_sample = nn.Sequential(
                nn.Conv2d(self.in_planes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = list()
        layers.append(block(layer_gates[0], self.in_planes, planes, stride, down_sample))
        self.in_planes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(layer_gates[i], self.in_planes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x


def resnet20(**kwargs):
    model = ResNet(BasicBlock, [3, 3, 3], **kwargs)
    return model


def main():
    input_x = torch.rand(32, 3, 32, 32)
    model = resnet20()
    output_y = model(input_x)
    print(output_y.size())


if __name__ == "__main__":
    main()
